package cn.rkylin.oms.sysOrder.service;

import cn.rkylin.apollo.common.util.HttpUtils;
import cn.rkylin.core.utils.SnoGerUtil;
import cn.rkylin.oms.common.dto.DBLog;
import cn.rkylin.oms.common.utils.CodeUtil;
import cn.rkylin.oms.common.utils.LogUtil;
import cn.rkylin.oms.resend.domain.AfterSaleResend;
import cn.rkylin.oms.resend.service.IAfterSaleResendService;
import cn.rkylin.oms.sysOrder.dao.ISysOrderDAO;
import cn.rkylin.oms.sysOrder.domain.SysOrder;
import cn.rkylin.oms.sysOrder.domain.SysOrderGoods;
import cn.rkylin.oms.sysOrder.vo.SysOrderVO;
import cn.rkylin.oms.sysrefund.servcie.ISysRefundService;
import cn.rkylin.oms.sysrefund.vo.SysRefundVO;
import cn.rkylin.oms.sysreturn.domain.SysReturn;
import cn.rkylin.oms.sysreturn.service.ISysReturnService;
import cn.rkylin.oms.system.shop.vo.ShopVO;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * 合并系统订单
 *
 * @author wangxing
 * @version 1.0
 * @created 2017.09.14
 */
@Service("combineSysOrderService")
public class CombineSysOrderService {

    //待合并的系统订单数据集
//    private List<SysOrderVO> sysOrderAllList = null;
    //系统订单按合并条件分组map
//    private Map<String, List<SysOrder>> sysOrderCombMap = null;
    //系统订单商品与系统订单关联关系map
//    private Map<String, List<SysOrderGoods>> sysOrderGoodsMap = null;

    @Autowired
    private ISysOrderDAO sysOrderDAO;

    /**
     * sysRefundService:系统退款单服务层.
     */
    @Autowired
    private ISysRefundService sysRefundService;

    /**
     * sysReturnService:系统退货单服务层.
     */
    @Autowired
    private ISysReturnService sysReturnService;

    /**
     * resendService:系统补发单服务层.
     */
    @Autowired
    private IAfterSaleResendService resendService;

    /**
     * OMS调用地址
     */
    @Value("${oms.address}")
    private String omsUrl;

    /**
     * 日志类
     */
    @Autowired
    private LogUtil logUtil;

    /**
     * 合并系统订单
     *
     * @param shopVO
     * @param buyerNick 家昵称 客户ID（手动下载用）
     * @param tradeCode 平台交易号（手动下载用）
     * @throws Exception
     */
    public void combineSysOrder(ShopVO shopVO, String buyerNick, String tradeCode) throws Exception {
        //店铺id
        String strShopId = shopVO.getShopId();
        //项目简称
        String strPrjShortName = shopVO.getPrjShortName();
        logUtil.info(new DBLog(strShopId, "系统订单自动下载", "跟踪日志", "shopAccount:" + shopVO.getShopAccount() + " 系统订单合并开始---------------------------------------"));
        //待合并的系统订单数据集
        List<SysOrderVO> sysOrderAllList = new ArrayList<SysOrderVO>();
        //系统订单按合并条件分组map
        Map<String, List<SysOrder>> sysOrderCombMap = new HashMap();
        //系统订单商品与系统订单关联关系map
        Map<String, List<SysOrderGoods>> sysOrderGoodsMap = new HashMap();

//1.1、获取待合并的系统订单数据集------------------------------------------------------------------------------------------
        Map<String, Object> orderIdAddMap = new HashMap();
        sysOrderAllList = getSysOrderList(strShopId, buyerNick, tradeCode, orderIdAddMap);
        if (sysOrderAllList != null && sysOrderAllList.size() > 0) {
            logUtil.info(new DBLog(strShopId, "系统订单自动下载", "跟踪日志", "获取待合并和无需合并系统订单数为:" + String.valueOf(sysOrderAllList.size())));
//1.2、获取当前系统订单数据集中的存在的售后事件、系统退款单、系统退货单以及系统补发单数据集------------------------------------------------------------------------------------------
            logUtil.info(new DBLog(strShopId, "系统订单自动下载", "跟踪日志", "校验待合并的系统订单售后单据开始"));
            getSysOrderEventList(orderIdAddMap, sysOrderAllList);
//1.3、获取系统订单商品数据集，并映射Map关系------------------------------------------------------------------------------------------
            logUtil.info(new DBLog(strShopId, "系统订单自动下载", "跟踪日志", "获取待合并的系统订单商品开始"));
            sysOrderGoodsMap = getSysOrderGoodsMap(orderIdAddMap);
//1.4、筛选出可以合并的和不需要合并的系统订单Map------------------------------------------------------------------------------------------
            logUtil.info(new DBLog(strShopId, "系统订单自动下载", "跟踪日志", "归类合并订单和无需合并订单开始"));
            sysOrderCombMap = getSysOrderCombMap(sysOrderAllList, strShopId);
//1.5、循环可合并和不需要合并的订单Map,分别赋值处理，并最终插入数据库------------------------------------------------------------------------------------------
//1.6、开始逐条合并订单插入到数据库-----------------------------------------------------------------------------------
//1.7、开始逐条更新合并前订单状态-----------------------------------------------------------------------------------
//1.8、开始逐条更新不需要合并的订单 进系统合并步骤抓态-----------------------------------------------------------------------------------
            setSysOrderCombInfo(strPrjShortName, sysOrderCombMap, sysOrderGoodsMap, strShopId);
        } else {
            logUtil.info(new DBLog(strShopId, "系统订单自动下载", "跟踪日志", "获取待合并和无需合并系统订单数为:0"));
        }
        logUtil.info(new DBLog(strShopId, "系统订单自动下载", "跟踪日志", "shopAccount:" + shopVO.getShopAccount() + " 系统订单合并结束---------------------------------------"));
    }

    /**
     * 获取待合并的系统订单数据集，并返回订单id累加数据集Map
     *
     * @param strShopId
     * @param buyerNick 买家昵称 客户ID（手动下载用）
     * @param tradeCode 平台交易号（手动下载用）
     * @return
     * @throws Exception
     */
    private List<SysOrderVO> getSysOrderList(String strShopId, String buyerNick, String tradeCode, Map<String, Object> orderIdAddMap) throws Exception {
        List<SysOrderVO> sysOrderAllList = new ArrayList<SysOrderVO>();
        try {
            //数据库参数
            Map<String, String> sysOrderMap = new HashMap();
            sysOrderMap.put("shopId", strShopId);
            sysOrderMap.put("orderStatus", "a");
            sysOrderMap.put("jobStep", "w");
            sysOrderMap.put("combStus", "n");
            sysOrderMap.put("isCancel", "n");
            sysOrderMap.put("isLock", "n");
            sysOrderMap.put("operStus", "au");
            if (StringUtils.isNotBlank(tradeCode)) {
                sysOrderMap.put("tradeCode", tradeCode);
            }
            if (StringUtils.isNotBlank(buyerNick)) {
                sysOrderMap.put("buyerNick", buyerNick);
            }
            sysOrderMap.put("orderBy", "job_step,buyer_nick,cons,cons_addr");//排序
            //获取待合并的系统订单数据集------------------------------------------------------------------------------------------
            sysOrderAllList = sysOrderDAO.selectSysOrderList(sysOrderMap);
            if (sysOrderAllList != null && sysOrderAllList.size() > 0) {
                //系统订单Id累加拼串，用于获取订单售后事件以及订单商品信息入参
                List<String> orderIdAddList = new ArrayList<String>();
                for (int orderIndex = 0; orderIndex < sysOrderAllList.size(); orderIndex++) {
                    orderIdAddList.add(sysOrderAllList.get(orderIndex).getOrderId());
                }

                orderIdAddMap.put("order_id", orderIdAddList);
                orderIdAddMap.put("isGift", "n");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            sysOrderAllList = null;
            orderIdAddMap = null;
            logUtil.error(new DBLog(strShopId, "系统订单自动下载", "跟踪日志", "获取待合并和无需合并系统订单异常:" + ex.getMessage()));
        }
        return sysOrderAllList;
    }

    /**
     * 获取系统订单商品数据集，并映射其与系统订单的Map关系
     *
     * @param map
     * @throws Exception
     */
    private Map<String, List<SysOrderGoods>> getSysOrderGoodsMap(Map<String, Object> map) throws Exception {
        Map<String, List<SysOrderGoods>> sysOrderGoodsMap = new HashMap();
        try {
            if (map != null && map.size() > 0) {
                //获取系统订单商品数据集------------------------------------------------------------------------------------------
                List<SysOrderGoods> sysOrderGoodsAllList = sysOrderDAO.selectSysOrderGoodsList(map);
                if (sysOrderGoodsAllList != null && sysOrderGoodsAllList.size() > 0) {
                    //系统订单商品实体
                    SysOrderGoods sysOrderGoods = new SysOrderGoods();
                    //系统订单id累加，作为主键
                    String strKey = "";
                    //系统订单商品临时列表
                    List<SysOrderGoods> sysOrderGoodsList = new ArrayList<SysOrderGoods>();
                    //循环系统订单 按合并订单条件各自组合Map
                    for (int orderGoodsIndex = 0; orderGoodsIndex < sysOrderGoodsAllList.size(); orderGoodsIndex++) {
                        sysOrderGoods = sysOrderGoodsAllList.get(orderGoodsIndex);
                        strKey = sysOrderGoods.getOrderId();
                        if (sysOrderGoodsMap.get(strKey) != null) {
                            sysOrderGoodsList = sysOrderGoodsMap.get(strKey);
                        } else {
                            sysOrderGoodsList = new ArrayList<SysOrderGoods>();
                        }
                        //累加系统订单商品
                        sysOrderGoodsList.add(sysOrderGoods);
                        sysOrderGoodsMap.put(strKey, sysOrderGoodsList);
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            sysOrderGoodsMap = null;
            logUtil.error(new DBLog("", "系统订单自动下载", "跟踪日志", "获取待合并的系统订单商品异常:" + ex.getMessage()));
        }

        return sysOrderGoodsMap;
    }

    /**
     * 过滤掉存在售后事件或系统退款单、系统退货单以及系统补发单的系统订单
     *
     * @param map
     * @throws Exception
     */
    private void getSysOrderEventList(Map<String, Object> map, List<SysOrderVO> sysOrderAllList) throws Exception {
        try {
            // 请求地址
            String requestUrl = omsUrl + "afterSale/getEventByOrderId.action";
            // 请求参数拼接
            String requestParams = "";
            // 请求数据
            String resJson = "";
            String strOrderId = "";
            for (int orderIndex = sysOrderAllList.size() - 1; orderIndex >= 0; orderIndex--) {
                strOrderId = sysOrderAllList.get(orderIndex).getOrderId();
                //调用系统退款单Service获取系统退款单
                SysRefundVO sysRefundVO = new SysRefundVO();
                sysRefundVO.setOrderId(strOrderId);
                sysRefundVO.setIsCancel("n");
                List<SysRefundVO> sysRefundVOList = sysRefundService.getSysRefundListByCondition(sysRefundVO);
                //存在系统退款单，移除当前订单
                if (sysRefundVOList != null && sysRefundVOList.size() > 0) {
                    sysOrderAllList.remove(orderIndex);
                    continue;
                }
                //调用系统退货单Service获取系统退货单
                List<SysReturn> sysReturnist = sysReturnService.selectSysReturnForSysOrder(strOrderId);
                //存在未废弃的系统退货单，移除当前订单
                if (sysReturnist != null && sysReturnist.size() > 0) {
                    sysOrderAllList.remove(orderIndex);
                    continue;
                }
                //调用系统补发单Service获取系统补发单
                List<AfterSaleResend> resendList = resendService.selectResendForSysOrder(strOrderId);
                //存在未废弃的系统补发单，移除当前订单
                if (resendList != null && resendList.size() > 0) {
                    sysOrderAllList.remove(orderIndex);
                    continue;
                }

//调用OMS工程中售后事件Controller 返回当前系统订单中存在售后事件的数据 入参为:strOrderId，返回：resultMap
                // 请求参数拼接
                requestParams = "orderId=" + strOrderId;
                // 转换响应数据
                Map<String, Object> resultMap = null;
                try {
                    // 请求数据
                    resJson = HttpUtils.sendByGet(requestUrl, requestParams);
                    // 转换响应数据
                    resultMap = JSON.parseObject(resJson, Map.class);
                } catch (Exception ex) {
                    ex.printStackTrace();
                    resultMap = null;
                }
                if (resultMap != null && resultMap.size() > 0) {
                    if (resultMap.containsKey("result")
                            && "success".equals(resultMap.get("result"))) {
                        sysOrderAllList.remove(orderIndex);
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            sysOrderAllList = null;
            logUtil.error(new DBLog("", "系统订单自动下载", "跟踪日志", "校验待合并的系统订单售后单据异常:" + ex.getMessage()));
        }
    }

    /**
     * 筛选出可以合并的和不需要合并的系统订单Map
     *
     * @param sysOrderAllList
     * @param strShopId
     * @return
     * @throws Exception
     */
    private Map<String, List<SysOrder>> getSysOrderCombMap(List<SysOrderVO> sysOrderAllList, String strShopId) throws Exception {
        Map<String, List<SysOrder>> sysOrderCombMap = new HashMap();
        try {
            //筛选出可以合并的和不需要合并的系统订单Map------------------------------------------------------------------------------------------
            //系统订单实体
            SysOrder sysOrder = new SysOrder();
            //合并订单条件累加，作为主键(BuyerNick + Cons + ConsAddr)
            String strCombKey = "";
            //系统订单临时列表
            List<SysOrder> sysOrderList = new ArrayList<SysOrder>();
            if (sysOrderAllList != null && sysOrderAllList.size() > 0) {
                //循环系统订单 按合并订单条件各自组合Map
                for (int orderIndex = 0; orderIndex < sysOrderAllList.size(); orderIndex++) {
                    sysOrder = sysOrderAllList.get(orderIndex);
                    strCombKey = sysOrder.getBuyerNick() + "-" + sysOrder.getCons() + "-" + sysOrder.getConsAddr();
                    if (sysOrderCombMap.get(strCombKey) != null) {
                        sysOrderList = sysOrderCombMap.get(strCombKey);
                    } else {
                        sysOrderList = new ArrayList<SysOrder>();
                    }
                    //累加系统订单
                    sysOrderList.add(sysOrder);
                    sysOrderCombMap.put(strCombKey, sysOrderList);
                }
            } else {
                sysOrderCombMap = null;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            sysOrderCombMap = null;
            logUtil.error(new DBLog(strShopId, "系统订单自动下载", "跟踪日志", "归类合并订单和无需合并订单异常:" + ex.getMessage()));
        }

        return sysOrderCombMap;
    }

    /**
     * 1.5、循环可合并和不需要合并的订单Map,分别赋值处理，待插入数据库做准备
     * 1.6、开始逐条合并订单插入到数据库
     * 1.7、开始逐条更新合并前订单状态
     * 1.8、开始逐条更新不需要合并的订单 进系统合并步骤抓态
     *
     * @throws Exception
     */
    private void setSysOrderCombInfo(String strPrjShortName, Map<String, List<SysOrder>> sysOrderCombMap, Map<String,
            List<SysOrderGoods>> sysOrderGoodsMap, String strShopId) throws Exception {
        try {
            if (sysOrderCombMap != null && sysOrderCombMap.size() > 0
                    && sysOrderGoodsMap != null && sysOrderGoodsMap.size() > 0) {
//1.5、循环可合并和不需要合并的订单Map,分别赋值处理------------------------------------------------------------------------------------------
                String strTradeCodeAdd = "";//平台交易号拼串
                String strRemarkAdd = "";//内部备注拼串
                String strCustRemarkAdd = "";//买家留言拼串
                Long intSellerFlag = 0L;//平台旗帜
                BigDecimal bdLgstFeeSum = BigDecimal.ZERO;//物流费
                BigDecimal bdPaidFeeSum = BigDecimal.ZERO;//支付金额
                BigDecimal bdServFeeSum = BigDecimal.ZERO;//服务费
                Date paidDate = null;//付款时间
                Date tempDate = null;//临时时间变量，用于比较付款时间
                SysOrder childSysorder = new SysOrder();//合并前订单
                SysOrder fatherSysorder = new SysOrder();//合并后订单
                List<SysOrder> childSysOrderList = new ArrayList<SysOrder>();
                List<SysOrderGoods> sysOrderGoodsList = new ArrayList<SysOrderGoods>();
                int iRes = 0;
                //循环可合并和不需要合并的订单Map
                for (Map.Entry<String, List<SysOrder>> entry : sysOrderCombMap.entrySet()) {
                    iRes = 0;
                    if (entry.getValue() != null && entry.getValue().size() > 1) {
                        //合并订单处理------------------------------------------------------------
                        childSysOrderList = entry.getValue();
                        logUtil.info(new DBLog(strShopId, "系统订单自动下载", "跟踪日志", "合并条件:" + entry.getKey() + " 系统订单合并处理开始*******************"));
                        strTradeCodeAdd = "";//平台交易号拼串
                        strRemarkAdd = "";//内部备注拼串
                        strCustRemarkAdd = "";//买家留言拼串
                        intSellerFlag = 0L;//平台旗帜

                        bdLgstFeeSum = BigDecimal.ZERO;//物流费
                        bdPaidFeeSum = BigDecimal.ZERO;//支付金额
                        bdServFeeSum = BigDecimal.ZERO;//服务费

                        paidDate = childSysOrderList.get(0).getPaidDate();//付款时间先任意取一个值
                        fatherSysorder = childSysOrderList.get(0);//合并后订单先取任意一个值
                        List<SysOrderGoods> fatherSysOrderGoodsList = new ArrayList<SysOrderGoods>();//合并后订单商品集合
                        List<String> beforeOrderIdAddList = new ArrayList<String>();//合并前订单id累加 用于生成合并订单后，更新合并前订单状态
                        //循环子订单
                        for (int orderIndex = 0; orderIndex < childSysOrderList.size(); orderIndex++) {
                            childSysorder = childSysOrderList.get(orderIndex);
                            logUtil.info(new DBLog(childSysorder.getOrderCode(), "系统订单自动下载", "跟踪日志", "平台交易号" + childSysorder.getTradeCode() + "子订单取值开始*******************"));
                            //对可以合并的订单做平台交易号，内部备注，买家留言累加拼串
                            strTradeCodeAdd += childSysorder.getTradeCode() + ",";
                            if (StringUtils.isNotBlank(childSysorder.getRemark())) {
                                strRemarkAdd += childSysorder.getRemark() + ",";
                            }
                            if (StringUtils.isNotBlank(childSysorder.getCustRemark())) {
                                strCustRemarkAdd += childSysorder.getCustRemark() + ",";
                            }
                            //合并订单 平台旗帜 判断 存在旗帜 就赋值为 6
                            if (childSysorder.getTbFlagCode() > 0) {
                                intSellerFlag = 6L;
                            }
                            //对可以合并的订单做金额合计
                            bdLgstFeeSum = bdLgstFeeSum.add(childSysorder.getLgstFee());
                            bdPaidFeeSum = bdPaidFeeSum.add(childSysorder.getPaidFee());
                            bdServFeeSum = bdServFeeSum.add(childSysorder.getServFee());
                            //对可以合并的订单合并订单商品明细
                            sysOrderGoodsList = sysOrderGoodsMap.get(childSysorder.getOrderId());
                            if (sysOrderGoodsList != null && sysOrderGoodsList.size() > 0) {
                                fatherSysOrderGoodsList.addAll(sysOrderGoodsList);
                            }

                            //按付款时间判断去最小的拍单时间的订单为合并后订单主单据信息
                            if (childSysorder.getPaidDate() != null) {
                                tempDate = childSysorder.getPaidDate();
                                if (tempDate != null && paidDate != null && tempDate.getTime() < paidDate.getTime()) {
                                    fatherSysorder = childSysOrderList.get(orderIndex);
                                    paidDate = tempDate;
                                }
                            }
                            //合并前订单id累加
                            beforeOrderIdAddList.add(childSysorder.getOrderId());
                            logUtil.info(new DBLog(childSysorder.getOrderCode(), "系统订单自动下载", "跟踪日志", "平台交易号" + childSysorder.getTradeCode() + "子订单取值结束*******************"));
                        }
                        //重新赋值合并后订单的平台交易号，内部备注，买家留言以及商品明细等...
                        fatherSysorder.setTradeCode(strTradeCodeAdd.substring(0, strTradeCodeAdd.length() - 1));
                        if (StringUtils.isNotBlank(strRemarkAdd)) {
                            fatherSysorder.setRemark(strRemarkAdd.substring(0, strRemarkAdd.length() - 1));
                        } else {
                            fatherSysorder.setRemark("");
                        }
                        if (StringUtils.isNotBlank(strCustRemarkAdd)) {
                            fatherSysorder.setCustRemark(strCustRemarkAdd.substring(0, strCustRemarkAdd.length() - 1));
                        } else {
                            fatherSysorder.setCustRemark("");
                        }
                        fatherSysorder.setTbFlagCode(intSellerFlag);
                        fatherSysorder.setLgstFee(bdLgstFeeSum);
                        fatherSysorder.setPaidFee(bdPaidFeeSum);
                        fatherSysorder.setServFee(bdServFeeSum);
                        fatherSysorder.setOrderId(SnoGerUtil.getUUID());
                        fatherSysorder.setOrderCode("OR" + strPrjShortName + CodeUtil.getCode());
                        fatherSysorder.setOrderStatus("a");
                        fatherSysorder.setCombStus("c");
                        fatherSysorder.setJobStep("c");
                        tempDate = new Date();
                        fatherSysorder.setCreateTime(tempDate);
                        fatherSysorder.setUpdateTime(tempDate);
                        fatherSysorder.setSysOrderGoodsList(fatherSysOrderGoodsList);
                        logUtil.info(new DBLog(fatherSysorder.getOrderCode(), "系统订单自动下载", "跟踪日志", "订单编号" + fatherSysorder.getOrderCode() + "合并后订单赋值阶段结束*******************"));
//1.6、开始逐条合并订单插入到数据库-----------------------------------------------------------------------------------
                        iRes = insertSysOrderInfo(fatherSysorder);
                        logUtil.info(new DBLog(fatherSysorder.getOrderCode(), "系统订单自动下载", "跟踪日志", "订单编号" + fatherSysorder.getOrderCode() + "合并后插入数据库阶段结束*******************"));
                        if (iRes > 0) {
//1.7、开始逐条更新合并前订单状态-----------------------------------------------------------------------------------
                            Map<String, Object> beforeOrderIdAddMap = new HashMap();//合并前订单id Map
                            beforeOrderIdAddMap.put("order_id", beforeOrderIdAddList);
                            beforeOrderIdAddMap.put("forderId", fatherSysorder.getOrderId());
                            updateBeforeSysOrderStatus(beforeOrderIdAddMap);
                            logUtil.info(new DBLog(fatherSysorder.getOrderCode(), "系统订单自动下载", "跟踪日志", "订单编号" + fatherSysorder.getOrderCode() + "更新合并前订单状态阶段结束*******************"));
                        }
                        logUtil.info(new DBLog(strShopId, "系统订单自动下载", "跟踪日志", "合并条件:" + entry.getKey() + " 系统订单合并处理结束*******************"));
                    } else if (entry.getValue() != null && entry.getValue().size() == 1) {
                        //非合并订单处理
                        childSysOrderList = entry.getValue();
                        logUtil.info(new DBLog(childSysOrderList.get(0).getOrderCode(), "系统订单自动下载", "跟踪日志", "非合并订单编号:" + childSysOrderList.get(0).getOrderCode() + " 更新非合并订单合并阶段状态处理开始*******************"));
//1.8、开始逐条更新不需要合并的订单 进系统合并步骤抓态 c -----------------------------------------------------------------------------------
                        //新进系统的订单更新完成合并步骤状态 jobstep='c'
                        if ("a".equals(childSysOrderList.get(0).getJobStep())) {
                            updateNoNeedCombSysOrderStatus(childSysOrderList.get(0).getOrderId(), childSysOrderList.get(0).getOrderCode());
                        }
                        logUtil.info(new DBLog(childSysOrderList.get(0).getOrderCode(), "系统订单自动下载", "跟踪日志", "非合并订单编号:" + childSysOrderList.get(0).getOrderCode() + " 更新非合并订单合并阶段状态处理结束*******************"));
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            logUtil.error(new DBLog(strShopId, "系统订单自动下载", "跟踪日志", "合并订单合并处理异常:" + ex.getMessage()));
        }
    }


    /**
     * 系统订单插入数据库
     *
     * @param sysOrder
     * @return
     * @throws Exception
     */
    private int insertSysOrderInfo(SysOrder sysOrder) throws Exception {
        int iRes = 0;
        try {
            if (sysOrder != null) {
                //合并后系统订单商品明细
                List<SysOrderGoods> sysOrderGoodsList = sysOrder.getSysOrderGoodsList();
                if (sysOrderGoodsList != null && sysOrderGoodsList.size() > 0)//保证系统订单一定有订单商品明细
                {
                    //合并后系统订单主表信息插入数据库
                    iRes = sysOrderDAO.insertSelectiveSysOrder(sysOrder);
                    if (iRes > 0) {
                        //记录日志
                        logUtil.info(new DBLog(sysOrder.getOrderCode(), "系统订单自动合并", "系统订单自动合并", "系统订单自动合并成功"));
                        for (int sysOrderGoodsIndex = 0; sysOrderGoodsIndex < sysOrderGoodsList.size(); sysOrderGoodsIndex++) {
                            SysOrderGoods sysOrderGoods = sysOrderGoodsList.get(sysOrderGoodsIndex);
                            sysOrderGoods.setOrderGoodsId(SnoGerUtil.getUUID());
                            sysOrderGoods.setOrderId(sysOrder.getOrderId());
                            sysOrderGoods.setCreateTime(new Date());
                            sysOrderGoods.setUpdateTime(new Date());
                            //合并后系统订单商品明细信息插入数据库
                            sysOrderDAO.insertSelectiveSysOrderGoods(sysOrderGoods);
                        }
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            iRes = 0;
            logUtil.error(new DBLog(sysOrder.getOrderCode(), "系统订单自动下载", "跟踪日志", "合并后订单插入数据库阶段异常:" + ex.getMessage()));
        }
        return iRes;
    }

    /**
     * 更新合并前系统订单合并状态
     *
     * @param beforeOrderIdAddMap
     * @return
     * @throws Exception
     */
    private int updateBeforeSysOrderStatus(Map<String, Object> beforeOrderIdAddMap) throws Exception {
        int iRes = 0;
        try {
            if (beforeOrderIdAddMap != null && beforeOrderIdAddMap.size() > 0) {
                iRes = sysOrderDAO.updateBeforeSysOrderStatus(beforeOrderIdAddMap);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            iRes = 0;
            logUtil.error(new DBLog("", "系统订单自动下载", "跟踪日志", "更新合并前订单状态阶段异常:" + ex.getMessage()));
        }
        return iRes;
    }

    /**
     * 更新不需要合并订单 进系统合并步骤状态
     *
     * @param strOrderId
     * @param strOrderCode
     * @return
     * @throws Exception
     */
    private int updateNoNeedCombSysOrderStatus(String strOrderId, String strOrderCode) throws Exception {
        int iRes = 0;
        try {
            if (StringUtils.isNotBlank(strOrderId)) {
                SysOrderVO sysOrder = new SysOrderVO();
                sysOrder.setOrderId(strOrderId);
                sysOrder.setJobStep("c");
                iRes = sysOrderDAO.updateByPrimaryKeySelectiveSysOrder(sysOrder);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            iRes = 0;
            logUtil.error(new DBLog(strOrderCode, "系统订单自动下载", "跟踪日志", "更新非合并订单合并阶段状态处理异常:" + ex.getMessage()));
        }
        return iRes;
    }


}
